package com.zcbl.toolkit.http.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Map;

/**
 * @author he peng
 * @create 2018/4/2 15:24
 * @see
 */
public class HttpRequestArgsErrorUtils {

    private HttpRequestArgsErrorUtils() {}

    /**
     * 日志打印请求参数错误 , 返回错误信息
     * @param logger
     * @param error
     * @return
     */
    public static String parseErrorMsg(Logger logger , BindingResult error) {
        Assert.notNull(logger , "logger == null");
        Assert.notNull(error , "error == null");
        Map<String , String> errorMsgMap = new HashMap<>(6);
        for (FieldError fieldError : error.getFieldErrors()) {
            errorMsgMap.put(fieldError.getField() , fieldError.getDefaultMessage());
        }
        String errorMsg = "";
        if (! CollectionUtils.sizeIsEmpty(errorMsgMap)) {
            errorMsg = JSON.toJSONString(errorMsgMap);
            logger.warn("Bad Request Args Error : {} " , errorMsg);
        }
        return errorMsg;
    }


    public static String parseErrorMsg(BindingResult error) {
        Assert.notNull(error , "error == null");
        Map<String , String> errorMsgMap = new HashMap<>(6);
        for (FieldError fieldError : error.getFieldErrors()) {
            errorMsgMap.put(fieldError.getField() , fieldError.getDefaultMessage());
        }
        String errorMsg = "";
        if (! CollectionUtils.sizeIsEmpty(errorMsgMap)) {
            errorMsg = JSON.toJSONString(errorMsgMap);
        }
        return errorMsg;
    }
}
